package com.yuexunit.mobilenurse.module.Patients.ui;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.ScannerNotClaimedException;
import com.honeywell.aidc.ScannerUnavailableException;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.honeywell.aidc.UnsupportedPropertyException;
import com.yuexunit.mobilenurse.R;
import com.yuexunit.mobilenurse.base.search.honeywell.HoneyWellConfig;
import com.yuexunit.mobilenurse.config.AppConfig;
import com.yuexunit.mobilenurse.module.Patients.ui.fragment.Frag_PatientList_HoneyWell;
import com.yuexunit.mobilenurse.util.ProUtil;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;

/**
 * Created by work-jx on 2016/2/26.
 */
public class Act_Main_HoneyWell extends KJActivity implements BarcodeReader.BarcodeListener,
        BarcodeReader.TriggerListener{
    @BindView(id = R.id.bottombar_content1, click = true)
    private RadioButton mRbtnContent1;
    @BindView(id = R.id.bottombar_content2, click = true)
    private RadioButton mRbtnContent2;
    @BindView(id = R.id.bottombar_content3, click = true)
    private RadioButton mRbtnContent3;

    private Frag_PatientList_HoneyWell contentFragment1;
    private KJFragment contentFragment2;
    private KJFragment contentFragment3;
    private KJFragment currentFragment;

    //HoneyWell扫描
    private BarcodeReader barcodeReader;

    @Override
    public void initData() {
        super.initData();
        // set lock the orientation
        // otherwise, the onDestory will trigger when orientation changes
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        barcodeReader = HoneyWellConfig.getBarcodeObject();
        AppConfig.ISOVER_PATIENT=false;
        contentFragment1 = new Frag_PatientList_HoneyWell();
        //contentFragment2 = new Frag_Notify();
        //contentFragment3 = new Frag_Upload();
    }

    @Override
    public void initWidget() {
        super.initWidget();
        changeFragment(contentFragment1);
    }

    @Override
    public void onResume(){
        super.onResume();
        Register(barcodeReader);
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();
            } catch (ScannerUnavailableException e) {
                e.printStackTrace();
                Toast.makeText(this, "Scanner unavailable", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            // release the scanner claim so we don't get any scanner
            // notifications while paused.
            barcodeReader.release();

            // unregister barcode event listener
            barcodeReader.removeBarcodeListener(this);

            // unregister trigger state change listener
            barcodeReader.removeTriggerListener(this);
        }
    }

//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        if (barcodeReader != null) {
//            // unregister barcode event listener
//            barcodeReader.removeBarcodeListener(this);
//
//            // unregister trigger state change listener
//            barcodeReader.removeTriggerListener(this);
//        }
//    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_main);
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.bottombar_content1:
                changeFragment(contentFragment1);
                break;
            case R.id.bottombar_content2:
                //changeFragment(contentFragment2);
                break;
            case R.id.bottombar_content3:
                // changeFragment(contentFragment3);
                break;
            default:
                break;
        }
    }

    public void changeFragment(KJFragment targetFragment) {
        currentFragment = targetFragment;
        super.changeFragment(R.id.main_content, targetFragment);
    }

    /**
     * 通过dispatchTouchEvent每次ACTION_DOWN事件中动态判断非EditText本身区域的点击事件，然后在事件中进行屏蔽。然后当点击不是EditText时候，进行隐藏键盘操作
     *
     * @param ev
     * @return
     */

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击的是输入框区域，保留点击EditText的事件\
                return false;
            } else {
                return true;
            }
        }
        return false;
    }

    //注册扫描监听返回
    private void Register(BarcodeReader barcodeReader)
    {
        if (barcodeReader != null) {

            // register bar code event listener
            barcodeReader.addBarcodeListener(this);

            // set the trigger mode to client control
            try {
                barcodeReader.setProperty(BarcodeReader.PROPERTY_TRIGGER_CONTROL_MODE,
                        BarcodeReader.TRIGGER_CONTROL_MODE_CLIENT_CONTROL);
            } catch (UnsupportedPropertyException e) {
                Toast.makeText(this, "Failed to apply properties", Toast.LENGTH_SHORT).show();
            }
            // register trigger state change listener
            barcodeReader.addTriggerListener(this);

            barcodeReader.setProperties(ProUtil.honewellConfig());
        }
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        final String codedata = barcodeReadEvent.getBarcodeData();
        aty.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(!codedata.equals(""))
                {
                    if(AppConfig.ISOVER_PATIENT) {
//                        if(codedata.length() ==Integer.valueOf(PreferenceHelper.readString(aty, AppConfig.JCI_INFO, AppConfig.JCI_WD_RULE)))
//                        {
//                            if(contentFragment1.JudgeVisitNo(codedata)) {
//                                PreferenceHelper.write(aty, AppConfig.CURRENT_PATIENT_INFO, AppConfig.CURRENT_PATIENT_VISITNO, codedata);
//                                AppConfig.VISITNO =codedata;
//                                showActivity(aty, Act_PatientDetail_HoneyWell.class);
//                            }
//                            else {
//                                Toast.makeText(aty, "非本病区病人!", Toast.LENGTH_LONG).show();
//                            }
//                        }
//                        else
//                        {
//                            Toast.makeText(aty, "请扫描病人腕带!", Toast.LENGTH_LONG).show();
//                        }
                    }
                    else{
                        Toast.makeText(aty, "病人列表尚未加载完!请加载完毕后,再扫描!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        ViewInject.toast("未识别条码!");
    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        try {
            // only handle trigger presses
            // turn on/off aimer, illumination and decoding
            barcodeReader.aim(triggerStateChangeEvent.getState());
            barcodeReader.light(triggerStateChangeEvent.getState());
            barcodeReader.decode(triggerStateChangeEvent.getState());

        } catch (ScannerNotClaimedException e) {
            e.printStackTrace();
            Toast.makeText(aty, "Scanner is not claimed", Toast.LENGTH_SHORT).show();
        } catch (ScannerUnavailableException e) {
            e.printStackTrace();
            Toast.makeText(aty, "Scanner unavailable", Toast.LENGTH_SHORT).show();
        }
    }
}
